<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Mindex extends MY_Model
{
    public function __construct()
    {
        parent::__construct();
    }
    
    public function getRestaurantLabelDb($time)
    {
        $timeupdate = $this->db->query("SELECT content FROM options WHERE tags = 'time_update_restaurant'")->row_object();
        if($time < $timeupdate->content)
        {
            $sql = "SELECT id,orderby,name,image,logo,share_facebook_url,hotline,phone_hotline FROM restaurant ORDER BY orderby ASC";
            $data = $this->db->query($sql)->result_array();
            
            $arr = array();
            foreach($data AS $item)
            {
				$item['name'] = stripslashes($item['name']);
                $sql_zone = "SELECT id,title FROM zone ORDER BY id ASC";
                $zone = $this->db->query($sql_zone)->result_array();
                $arr_zone = array();
                foreach($zone AS $itemz)
                {
                    $sql_address = "SELECT ra.id,ra.address,ra.phone,ra.latitude,ra.longitude FROM restaurant_address AS ra LEFT JOIN zone AS z ON z.id = ra.id_zone WHERE ra.restaurant_id = ".$item['id']." AND z.id = ".$itemz['id']." ORDER BY ra.id ASC";
                    $address = $this->db->query($sql_address)->result_array();
                    if(!in_array($address, array(null, '', '0', 0))){
                        $itemz['list'] = $address;
                        $arr_zone[] = $itemz;
                    }
                }
                $item['address'] = $arr_zone;
                
                $arr['id_'.$item['id']] = $item;
            }
            
            $arr['time_update'] = $timeupdate->content;
            return (object)array('status' => 200, 'data' => (array)$arr);
        }else{
            return (object)array('status' => 201, 'data' => '');
        }
    }
    
    public function getStaticDataDb($time)
    {
        $timeupdate = $this->db->query("SELECT content FROM options WHERE tags = 'time_update_api_static'")->row_object();
        if($time < $timeupdate->content)
        {
            $slides = $this->db->query("SELECT slides FROM slides LIMIT 1")->row_array();
            $delivery = $this->db->query("SELECT features,title,content FROM home_delivery LIMIT 1")->row_array();
            $faq = $this->db->query("SELECT question,answer FROM faq ORDER BY id DESC")->result_object();
            
            $logo_gpeople = $this->db->query("SELECT content FROM options WHERE tags = 'logo_gpeople'")->row_object();
            $fanpage = $this->db->query("SELECT content FROM options WHERE tags = 'fanpage'")->row_object();
            $hotline = $this->db->query("SELECT content FROM options WHERE tags = 'hotline'")->row_object();
            $distance = $this->db->query("SELECT content FROM options WHERE tags = 'distance'")->row_object();
			$urlhomeicook = $this->db->query("SELECT content FROM options WHERE tags = 'urlhomeicook'")->row_object();
            $link_down_app = $this->db->query("SELECT content FROM options WHERE tags = 'link_down_app'")->row_object();
			$for_review = $this->db->query("SELECT content FROM options WHERE tags = 'for_review'")->row_object();
			$version = $this->db->query("SELECT content FROM options WHERE tags = 'version'")->row_object();
            $slide_arr = array();
            foreach(json_decode($slides['slides']) AS $item)
            {
                $slide_arr[] = $item;
            }
            
            $faq_fix = array();
            $i = 0;
            foreach($faq AS $key=>$value){
                $faq_fix[$i]['question'] = $value->question;
                $faq_fix[$i]['answer'] = strip_tags(html_entity_decode($value->answer, ENT_QUOTES, "UTF-8"));
                $i = $i + 1;
            }
            
            $incentive_province_list = array();
            $incentive_province_id = $this->db->query("SELECT content FROM options WHERE tags = 'incentive_province_list'")->row_object()->content;
            //die(print_r(json_decode($incentive_province_id)));
            foreach(json_decode($incentive_province_id) AS $key => $value){
                $incentive_province_list[$key] = $this->db->query("SELECT provinceid,name FROM vn_province WHERE provinceid = '$value'")->row_array();
            }
            
            $arr = array(
                'slides' => $slide_arr,
                'delivery' => $delivery,
                'faq' => $faq_fix,
                'logo_gpeople' => $logo_gpeople->content,
                'fanpage' => $fanpage->content,
                'hotline' => $hotline->content,
                'time_update' => $timeupdate->content,
				'distance' => $distance->content,
				'urlhomeicook' => $urlhomeicook->content,
                'link_down_app' => $link_down_app->content,
				'for_review' => $for_review->content,
				'version' => $version->content,
                'incentive_province_list' => $incentive_province_list
            );
            return (object)array('status' => 200, 'data' => (object)$arr);
        }else{
            return (object)array('status' => 201, 'data' => '');
        }
    }
    
    public function getProvinceDb()
    {
        $province = $this->db->query("SELECT * FROM vn_province ORDER BY provinceid ASC")->result_object();
        $district =  $this->db->query("SELECT * FROM vn_district ORDER BY districtid ASC")->result_object();
        //Đồng bộ province với gpeople
        $url=(string)'http://g-people.ggg.com.vn/provincelist';
        $apiProvince=json_decode(file_get_contents($url));
        $url=(string)'http://g-people.ggg.com.vn/districtlist';
        $apiDistrict=json_decode(file_get_contents($url));
//        $arr=$apiDistrict->data;var_dump((array)$arr[0]);die;
        if(count($province)!= count($apiProvince->data) || count($district)!= count($apiDistrict->data))
        {
          //Truncate table
          $this->db->query('Truncate table vn_province');
          $this->db->query('Truncate table vn_district');
//          var_dump($apiProvince->data);die;
          //Insert table province
          foreach($apiProvince->data as $value)
          {
             
              $array=(array)$value;
              $this->db->insert('vn_province',$array);
          }    
          
           //Insert table district
          foreach($apiDistrict->data as $value)
          {
              $array=(array)$value;
              $this->db->insert('vn_district',$array);
          }    
        }
         //Trả dữ liệu(giữ như cũ)
        $province = $this->db->query("SELECT * FROM vn_province ORDER BY provinceid ASC")->result_object();
        foreach($province AS $key => $val){
            $district = $this->db->query("SELECT districtid,name,type,provinceid FROM vn_district WHERE provinceid = ".$val->provinceid)->result_array();
            $val->district = $district;
            $data[] = $val;
        }
        return $data;
    }
    
    public function getRestaurantDetailDb($restaurant_id)
    {
        $sql = "SELECT id,name,image,logo,share_facebook_url,hotline,phone_hotline FROM restaurant WHERE id = ".$restaurant_id." ORDER BY orderby ASC";
        $data = $this->db->query($sql)->row_array();
        
        $sql_zone = "SELECT id,title FROM zone ORDER BY id ASC";
        $zone = $this->db->query($sql_zone)->result_array();
        $arr_zone = array();
        foreach($zone AS $item)
        {
            $sql_address = "SELECT ra.id,ra.address,ra.phone,ra.latitude,ra.longitude FROM restaurant_address AS ra LEFT JOIN zone AS z ON z.id = ra.id_zone WHERE ra.restaurant_id = ".$data['id']." AND z.id = ".$item['id']." ORDER BY ra.id ASC";
            $address = $this->db->query($sql_address)->result_array();
            if(!in_array($address, array(null, '', '0', 0))){
                $item['list'] = $address;
                $arr_zone[] = $item;
            }
        }
        $data['address'] = $arr_zone;
        
        return (object)array('status' => 200, 'data' => (array)$data);
    }
	
	public function getIncentiveDetail($id){
		return $this->db->query('SELECT * FROM incentive_restaurant WHERE id = '.$id.' LIMIT 1')->row_object();
	}
	
	public function getNearRestaurant($restaurantid,$locationid)
    {
		if( !in_array( $restaurantid,array('',null,0) ) ){
			$sql = "SELECT id,name AS restaurantname,logo FROM restaurant WHERE id = ".$restaurantid;
		}else{
			$sql = "SELECT id,name AS restaurantname,logo FROM restaurant ORDER BY orderby ASC";
		}
		$data = $this->db->query($sql)->result_object();
		//echo '<pre>';die(print_r($data));
		$arr = array();
		foreach($data AS $el=>$le)
		{
			if( !in_array( $locationid,array('',null,0) ) ){
				$sql_address = "SELECT ra.id,ra.address,ra.phone,ra.latitude,ra.longitude FROM restaurant_address AS ra WHERE ra.restaurant_id = ".$le->id." AND ra.id = ".$locationid." ORDER BY ra.id ASC";
			}else{
				$sql_address = "SELECT ra.id,ra.address,ra.phone,ra.latitude,ra.longitude FROM restaurant_address AS ra WHERE ra.restaurant_id = ".$le->id." ORDER BY ra.id ASC";
			}
			$address = $this->db->query($sql_address)->result_object();
			foreach ( $address AS $il=>$li ){
				$address[$il]->restaurantid = $le->id;
				$address[$il]->logo = $le->logo;
				$address[$il]->restaurantname = $le->restaurantname;
			}
			$data[$el]->address = $address;
			$arr = array_merge($arr, $address);
		}
		return ($arr);
    }
    
    public function getKeyDb($user_id,$key,$type)
    {
        if($type == 1){
            $key_type = 'key_ios';    
        }else if($type == 2){
            $key_type = 'key_android';
        }else if($type == 3){
            $key_type = 'key_winphone';
        }
        
        $data = array(
            $key_type => $key
        );
        
        if( !in_array($user_id, array(null, '')) && $user_id != 0 )
        {
            $data['user_id'] = $user_id;
        }
        
        $count_x = $this->db->query("SELECT user_id FROM `push_key` WHERE ".$key_type." = '".$key."' AND user_id = '".$user_id."'")->num_rows();
        if($count_x > 0){
            return array('status' => 201, 'description' => 'Key và UserID đã tồn tại');
        }
        
        $count = $this->db->query("SELECT * FROM `push_key` WHERE ".$key_type." = '".$key."'")->num_rows();
        $count_user = $this->db->query("SELECT user_id FROM `push_key` WHERE user_id = ".$user_id)->num_rows();
        if($count > 0){ //key đã tồn tại
            $this->db->query("DELETE FROM push_key WHERE ".$key_type." = '".$key."'");
            if($count_user > 0){ //user đã tồn tại
                $this->db->delete('push_key', "user_id = ".$user_id);
                $this->db->insert('push_key', $data);    
            }else{
                $this->db->insert('push_key', $data);
            }
        }else{
            if($count_user > 0){ //user đã tồn tại
                $this->db->delete('push_key', "user_id = ".$user_id);
                $this->db->insert('push_key', $data);    
            }else{
                $this->db->insert('push_key', $data);
            }
        }
        return array('status' => 200, 'description' => 'Insert thành công');
    }
    
    public function pushByTokenDb($message, $key, $type)
    {
        if($type == 1) //ios
        {
            $this->push_ios($message,array($key));
            return array('status' => 200, 'description' => 'Push thành công iOS');
        }elseif($type == 2){ //android
            $this->send_push_notification(array($key),$message);
            return array('status' => 200, 'description' => 'Push thành công Android');
        }
    }
    
    private function push_ios($notification,$arr_ios)
    {
        //$TEXT_ALERT =  isset($_REQUEST['mes'])? $_REQUEST['mes'] : 'Bạn có tin nhắn từ VTV';
        $TEXT_ALERT = $notification;
        $BADGE = 1;
        $SOUND = 'default';
        $SERVER_ID = '';
        $NAME = '';
        $SANBOX = 1;
        //e1edea3201896340c0a3ee204159dab77e52107b86671c35158600b88e217562
        //$token1 = 'd35adca952d11e59e436edd93293d8cc5ac1c9f161fe480f9ad15258c5f6ff71';
        //$deviceTokenList = array($token1);
        $deviceTokenList = $arr_ios;
        $payload = array();
        $payload['aps'] = array('alert' => $TEXT_ALERT, 'badge' => $BADGE, 'sound' => $SOUND);
        $payload['server'] = array('serverId' => $SERVER_ID, 'name' => $NAME);
        $payload = json_encode($payload);
        
        
        
        if ($SANBOX) {
        	$apnsHost = 'gateway.sandbox.push.apple.com';
        }else{
        	$apnsHost = 'gateway.push.apple.com';
        }
        $apnsPort = 2195;
        $apnsCert = PROJECT_PATH.'/push_development.pem';
        
        //make connection
        $streamContext = stream_context_create();
        stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
        $apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
        
        if ($apns == NULL || $error != NULL) {
        	//echo "Error when connect to " . $apnsPort . ', err string ' . $errorString;
        	return 201;
        }

        
        //echo "connect success\n";
        foreach ($deviceTokenList as $deviceToken) {
        	//echo "Add token $deviceToken\n";
        	//build message
        	$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
        	fwrite($apns, $apnsMessage);
        }
        @socket_close($apns);
        fclose($apns);
        
        return 200;
    }
    
    private function send_push_notification($registation_ids, $message) {
        //die(GOOGLE_API_KEY);
        //die('d');
        $url = 'https://android.googleapis.com/gcm/send';

        $fields = array(
            'registration_ids' => $registation_ids,
            'data' => array( 'price' => $message ),
        );
        $headers = array(
            'Authorization: key='.GOOGLE_API_KEY,
            'Content-Type: application/json'
        );
        //print_r($headers);
        // Open connection
        $ch = curl_init();

        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            //die('Curl failed: ' . curl_error($ch));
            return 201;
        }

        // Close connection
        curl_close($ch);
        //echo $result;
        return 200;
    }
}